package com.ztc.test;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.apache.poi.xwpf.converter.core.BasicURIResolver;
import org.apache.poi.xwpf.converter.core.FileImageExtractor;
import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;
import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.w3c.dom.Document;

public class WordToHtml {
	
	public static void main(String[] args) {
		try {
//			WordToHtml.PoiWord07ToHtml();
			WordToHtml.PoiWord03ToHtml();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * word07版本(.docx)转html poi:word07在线预览
	 */
	public static void PoiWord07ToHtml() throws IOException {

		String path = "C:\\Users\\Administrator\\Desktop\\";
		String file = "C:\\Users\\Administrator\\Desktop\\2.docx";
		String file2 = "C:\\Users\\Administrator\\Desktop\\word07.html";
		File f = new File(file);
		if (!f.exists()) {
			System.out.println("Sorry File does not Exists!");
		} else {
			if (f.getName().endsWith(".docx") || f.getName().endsWith(".DOCX")) {
				// 读取文档内容
				InputStream in = new FileInputStream(f);
				XWPFDocument document = new XWPFDocument(in);

				File imageFolderFile = new File(path);
				// 加载html页面时图片路径
				XHTMLOptions options = XHTMLOptions.create()
						.URIResolver(new BasicURIResolver("./"));
				// 图片保存文件夹路径
				options.setExtractor(new FileImageExtractor(imageFolderFile));
				OutputStream out = new FileOutputStream(new File(file2));
				XHTMLConverter.getInstance().convert(document, out, options);
				out.close();
			} else {
				System.out.println("Enter only MS Office 2007+ files");
			}
		}

	}

	/**
	 * word03版本(.doc)转html poi:word03在线预览
	 */
	public static void PoiWord03ToHtml()
			throws IOException, ParserConfigurationException, TransformerException {
		final String path = "C:\\Users\\Administrator\\Desktop\\";
		final String file = "C:\\Users\\Administrator\\Desktop\\2.doc";
		InputStream input = new FileInputStream(file);
		HWPFDocument wordDocument = new HWPFDocument(input);
		WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(
				DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
		wordToHtmlConverter.setPicturesManager(new PicturesManager() {
			public String savePicture(byte[] content, PictureType pictureType, String suggestedName,
					float widthInches, float heightInches) { // 图片在html页面加载路径
				return "image\\" + suggestedName;
			}
		});
		wordToHtmlConverter.processDocument(wordDocument);
		// 获取文档中所有图片
		List pics = wordDocument.getPicturesTable().getAllPictures();
		if (pics != null) {
			for (int i = 0; i < pics.size(); i++) {
				Picture pic = (Picture) pics.get(i);
				try {// 图片保存在文件夹的路径
					pic.writeImageContent(new FileOutputStream(path + pic.suggestFullFileName()));
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}
			}
		}
		// 创建html页面并将文档中内容写入页面
		Document htmlDocument = wordToHtmlConverter.getDocument();
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		DOMSource domSource = new DOMSource(htmlDocument);
		StreamResult streamResult = new StreamResult(outStream);
		TransformerFactory tf = TransformerFactory.newInstance();
		Transformer serializer = tf.newTransformer();
		serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
		serializer.setOutputProperty(OutputKeys.INDENT, "yes");
		serializer.setOutputProperty(OutputKeys.METHOD, "html");
		serializer.transform(domSource, streamResult);
		outStream.close();
		String content = new String(outStream.toString("UTF-8"));
		OutputStream os = new FileOutputStream(new File(path, "word03.html"));
		os.write(content.getBytes());
		os.close();
	}
}
